/*
 * @Author: your name
 * @Date: 2021-10-12 10:49:10
 * @LastEditTime: 2021-10-12 11:42:26
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \X\1km\driver\sensor\pules_cnt\pules_cnt.c
 */
#include "pules_cnt.h"
#include "../boardio.h"

uint32_t PulesCnt[PULSE_NUM];


uint8_t xp_pules_get_gpio_states(void);
void xp_pules_cnt_thread(void *arg);


int xp_pules_init(void)
{
    if (0 != aos_task_new("xp_pules_cnt_thread", xp_pules_cnt_thread, NULL, 2048)){
		return -1;
	}
}

int xp_pules_Deinit(void)
{
    for (int i = 0; i < PULSE_NUM; i++)
    {
        PulesCnt[i] = 0;
    }
    
    if (0 != aos_task_delete("xp_pules_cnt_thread")){
		return -1;
	}
    return 0;
}
/**
 * 脉冲计数线程
 *
 * @param[in]  *arg
 *
 * @return  void
 */
void xp_pules_cnt_thread(void *arg)
{
    uint8_t CurIoState = 0, LastIoState = 0;
    for (;;)
    {
        CurIoState = xp_pules_get_gpio_states();
        if (CurIoState != LastIoState){                 //仅状态发生变化后才进行计数
            LastIoState = CurIoState ^ LastIoState;
            for (uint8_t i = 0; i < PULSE_NUM; i++){
                if ((0x01 << i) & LastIoState){
                    PulesCnt[i]++;
                }
            }
            LastIoState = CurIoState;
        }
        aos_msleep(10);
    }
}
/**
 * 获取脉冲IO组状态
 * 
 * @return  void
 */
uint8_t xp_pules_get_gpio_states(void)
{
    uint8_t ret = 0;
    for (int i = 0; i < PULSE_NUM; i++){
        ret |= xp_boardIO_get(i + 1) << i;
    }
    return ret;
}

int xp_pules_clear(uint8_t id)
{
    if (id < PULSE_NUM){
        PulesCnt[id] = 0;
    }else{
        return -1;
    }
    return 0;
}

uint32_t xp_pules_get_cnt(uint8_t id)
{
    if (id < PULSE_NUM){
        return PulesCnt[id];
    }else{
        return UINT32_MAX;
    }
}
